﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Antioch.Base;

namespace Jemgine.Engine
{
    [Jemgine.Engine.Category("System"), Jemgine.Engine.Component]
    public class UseAction : Jemgine.Engine.EntityComponent
    {
        [System.ComponentModel.Editor(typeof(Data.TextureEditor), typeof(System.Drawing.Design.UITypeEditor))]
        public String Icon { get; set; }

        public UseAction()
        {
            AddInput("Contact", null);
            AddOutput("Used", null);
            Icon = "controller/xboxControllerButtonY";
        }

        public override void FireTerminal(int InputID, Jemgine.Data.ScriptPayload Payload)
        {
            if (InputID != 0) return;
            GameStateModule GameState = Sim.GetModule<GameStateModule>();
            if (GameState != null && Payload.SenderRef == GameState.Player)
            {
                ActionIconModule Module = Sim.GetModule<ActionIconModule>();
                if (Module == null) return;
                Module.SetAction(this, Payload);
            }
        }

        internal void Used(Jemgine.Data.ScriptPayload Payload)
        {
            OutputTerminals[0].Fire(Payload);
        }
    }

    public class ActionIconModule : Jemgine.Engine.Module
    {
        public UseAction Action = null;
        public Jemgine.Data.ScriptPayload Payload;

        public override void PreUpdate()
        {
            Action = null;
        }

        public override void Draw(Renderer.RenderEffect Effect, Renderer.VertexPusher Pusher)
        {
            if (Action != null)
            {
                Effect.Texture = Sim.EpisodeContent.GetTexture(Action.Icon);
                Effect.Technique = "DrawFullbright";
                Effect.PushMatrix(
                    Matrix.CreateScale(4.0f) *
                    Matrix.CreateTranslation(
                    new Vector3(Vector2.Transform(Action.Position, Action.GetFullTransform()), 0.0f)));
                Pusher.DrawSprite(false);
                Effect.PopMatrix();
            }
        }

        public void SetAction(UseAction Action, Jemgine.Data.ScriptPayload Payload)
        {
            GameStateModule GameState = Sim.GetModule<GameStateModule>();
            if (GameState == null) return;
            if (Payload.SenderRef != GameState.Player) return;

            this.Action = Action;
            this.Payload = Payload;
        }

        public void UseActionPressed()
        {
            if (Action != null) Action.Used(Payload);
        }
    }
}
